package com.SpringBoot.filter;

import cn.hutool.core.util.StrUtil;
import com.SpringBoot.bean.User;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @title: LogoutFilter
 * @Author HuangYan
 * @Date: 2022/2/24 15:49
 * @Version 1.0
 * @Description: 推出登陆过滤器
 */
@Slf4j
public class LogoutFilter extends org.apache.shiro.web.filter.authc.LogoutFilter{

    private String loginUrl;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        try {
            Subject subject = getSubject(request, response);
            String redirectUrl = getRedirectUrl(request, response, subject);
            Session session = subject.getSession();
            User user = null;
            if (session != null) {
                user = (User) session.getAttribute("user");
                session.removeAttribute("username");
                session.removeAttribute("type");
                session.removeAttribute("user");
                // 退出登录
                subject.logout();
                issueRedirect(request, response, redirectUrl);
                log.info("用户退出成功，用户名：{}", user.getLoginName());
            }
        } catch (Exception e) {
            log.error("退出登录异常", e);
        }
        return false;
    }

    /**
     * 退出跳转URL
     */
    @Override
    protected String getRedirectUrl(ServletRequest request, ServletResponse response, Subject subject)
    {
        String url = getLoginUrl();
        if (StrUtil.isNotEmpty(url))
        {
            return url;
        }
        return super.getRedirectUrl(request, response, subject);
    }
}
